package com.jzo2o.foundations.service.impl;

import cn.hutool.json.JSONUtil;
import com.jzo2o.foundations.model.domain.ServeSearch;
import com.jzo2o.foundations.service.IServeSearchEsService;

import com.mysql.cj.QueryBindings;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * \* User: chy
 * \* Date: 2025/9/29  16:12
 * \* Description:
 * \
 */
@Service
@Slf4j
public class ServeSearchEsServiceImpl implements IServeSearchEsService {

    @Resource
    private RestHighLevelClient esClient;

    /**
     * 小程序端所用es进行搜索的功能
     *
     * @param cityCode 城市编码
     * @param serveTypeId 服务类型id
     * @return 服务列表
     */
    @Override
    public List<ServeSearch> querySaleServeSearchList(String cityCode, String keyword, Long serveTypeId) {
        List<ServeSearch> serveSearches = new ArrayList<>();
        try {
            // 1.创建查询请求
            SearchRequest searchRequest = new SearchRequest("serve");
            // 2.构建查询条件
            BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
            // 2.1 添加用户输入的搜索条件 服务的类型名字和服务的名字进行分词查询
            if(StringUtils.hasText(keyword)){
                boolQuery.must(QueryBuilders.multiMatchQuery(keyword,"serveItemName","serveTypeName"));
            }else {
                boolQuery.must(QueryBuilders.matchAllQuery());
            }
            // 2.2 添加服务类型id的查询条件
            if(serveTypeId != null){
                boolQuery.filter(QueryBuilders.termQuery("serveTypeId",serveTypeId));
            }
            // 2.3 添加城市编码的查询条件
            if(StringUtils.hasText(cityCode)){
                boolQuery.filter(QueryBuilders.termQuery("cityCode",cityCode));
            }
            searchRequest.source().query(boolQuery);
            // 3.拿到结果进行处理并返回
            SearchResponse response = esClient.search(searchRequest, RequestOptions.DEFAULT);
            // 3.1 拿到结果进行处理并返回
            SearchHit[] searchHits = response.getHits().getHits();
            for (SearchHit searchHit : searchHits) {
                ServeSearch serveSearch = JSONUtil.toBean(searchHit.getSourceAsString(), ServeSearch.class);
                serveSearches.add(serveSearch);
            }
        } catch (IOException e) {
            log.error("小程序端用户搜索功能查询失败:{}",e);
        }
        return serveSearches;
    }
}
